import {createSlice} from "@reduxjs/toolkit";
import axios from "axios";

const billStore = createSlice({
    name: "billStore",
    initialState: {
        billList: []
    },
    reducers: {
        setBillList(state, action) {
            state.billList = action.payload
        },
        //添加同步方法
        addBill(state, action) {
            state.billList.push(action.payload)
        }
    }
})

const {setBillList, addBill} = billStore.actions

//异步方法获取数据
const getBillList = () => {
    return async (dispatch) => {
        const res = await axios.get("http://localhost:8888/ka")
        dispatch(setBillList(res.data))
    }
}
// 异步方法添加数据
const addBillAsync = (data) => {
    return async (dispatch) => {
        const res = await axios.post("http://localhost:8888/ka", data)
        // 触发同步方法
        dispatch(addBill(res.data))
    }
}
//按需导出
export {getBillList, addBillAsync}

// 默认导出reducer
const reducer = billStore.reducer;
export default reducer;
